import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { FeedbackEntity } from "./feedback.entity";
import { Repository } from "typeorm";
import { UserEntity } from "../user/user.entity";
import { BusinessException } from "~/common/exceptions/biz.exception";

@Injectable()
export class FeedbackService {
	constructor(
		@InjectRepository(FeedbackEntity)
		private readonly feedbackRepository: Repository<FeedbackEntity>,
		@InjectRepository(UserEntity)
		private readonly userRepository: Repository<UserEntity>
	) { }

	async add(content: string, userId: number): Promise<void> {
		// 保存反馈内容，关联用户
		const user = await this.userRepository.findOne({ where: { id: userId } });

		if (!user) {
			throw new BusinessException("用户不存在")
		}

		const feedback = new FeedbackEntity();
		feedback.content = content;
		feedback.user = user;
		await this.feedbackRepository.save(feedback);
	}

	async addByOne(content: string): Promise<void> {
		// 查询用户的第一个用户
		const users = await this.userRepository.find({ order: { id: "ASC" }, take: 1 });

		if (users.length === 0) {
			throw new BusinessException("用户不存在")
		}

		const user = users[0];

		await this.add(content, user.id);
	}
}